const pool = require('../utils/utils.js')
const jwt = require('jsonwebtoken')

const login = async (ctx,next)=> {
    const {openId,nickName,password,role} = ctx.request.body;

    if(openId){
        let querySr = `select * from user where openid="${openId}"`
        let r = await new Promise((resolve, reject) => {
            pool.query(querySr, (err, result) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(result)
                }
            })
        })
        if(Array.isArray(r) && r.length>0){
            let data = r[0]
            delete data.openid
            delete data.password
            let token = jwt.sign({...data},"cczztt",{expiresIn:'48h'})
            ctx.body = {
                code:0,
                data:data,
                token:token
            }
            next()
        }else{
            ctx.body = {
                code:400,
                msg:"没有这个用户",
            }
            next()
        }
    }else if(nickName && password){
        let querySr = `select * from user where nickname="${nickName}" and password="${password}"`
        let r = await new Promise((resolve, reject) => {
            pool.query(querySr, (err, result) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(result)
                }
            })
        })
        if(Array.isArray(r) && r.length>0){
            let data = r[0]
            let token = jwt.sign({...data},"cczztt",{expiresIn:'48h'})
            ctx.body = {
                code:200,
                data:data,
                token:token
            }
            next()
        }else{
            ctx.body = {
                code:400,
                msg:"用户名或密码错误",
            }
            next()
        }
    }else{
        ctx.body = {
            code:400,
            msg:"参数错误",
        }
        next()
    }
}

module.exports = login